package com.fjwt.gz.coupon.hkpay;


import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.third.bo.CouponAwardBo;
import com.fjwt.gz.core.third.interfaces.ICheckService;
import com.fjwt.gz.coupon.hkpay.hkpayutil.HkApiClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class HkpayCheckBillService implements ICheckService {
    //TODO  注意：：注意：：上面要记得封装一层，进行分发，到这一层
    //TODO  上面封装的一层自动注入这个service，调用下载账单的方法，然后返回对应的数据，上一层进行不同的通道的处理
    //TODO  注意这个是海科单独的下载的账单接口，上一层要封装一层，通过ifcode进行分发，



    public JSONObject getBill(CouponAwardBo couponAwardBo) {
        log.info("开始下载海科对账单，卡券数据信息：{}", couponAwardBo);
        if (StringUtils.isBlank(couponAwardBo.getAuthConfig())) {
            log.warn("海科通道配置参数为空: {}", couponAwardBo.getAuthConfig());
            throw new BizException("下载海科对账单---海科通道配置参数为空");
        }

        if (StringUtils.isBlank(couponAwardBo.getPayConfig())) {
            log.warn("支付配置参数为空");
            throw new BizException("下载海科对账单---支付配置参数为空");
        }
        JSONObject payAuthConfigJson = JSON.parseObject(couponAwardBo.getPayConfig());
        Integer couponId = payAuthConfigJson.getInteger("stockId");
        log.info("活动批次号: {}", couponId);
        if (couponId == null) {
            log.warn("批次号为空");
            throw new BizException("下载海科对账单---批次号为空");
        }
        try {
            JSONObject responseData = authConnect(couponAwardBo.getAuthConfig(), couponId);
            log.info("海科对账拉取账单数据：{}", responseData);
            if (responseData == null) {
                log.warn("海科拉取账单数据为空");
                throw new BizException("下载海科对账单---海科拉取账单数据为空");
            }
            //返回下载账单的结果
            return responseData;

        } catch (Exception e) {
            log.error("对账处理异常，{}", e.getMessage());
        }

        return null;
    }


    /**
     * 海科通道连接
     */
    public JSONObject authConnect(String authConfig, Integer couponId) throws BizException {
        JSONObject authConfigJson = JSONObject.parseObject(authConfig);

        try {
            JSONObject reqJson = new JSONObject();
            reqJson.put("stockId", couponId);
            reqJson.put("offset", 0);
            reqJson.put("limit", 100);

            // 检查 authConfigJson 中的键是否存在
            if (!authConfigJson.containsKey("clientKey") || !authConfigJson.containsKey("securityKey") ||
                    !authConfigJson.containsKey("address") || !authConfigJson.containsKey("service") || !authConfigJson.containsKey("version")) {
                throw new BizException("配置信息不完整");
            }

            HkApiClient apiClient = new HkApiClient(authConfigJson.getString("clientKey"),
                    authConfigJson.getString("securityKey"), authConfigJson.getString("address"));
            HkApiClient.ApiResponse<JSONObject> response = apiClient.request(authConfigJson.getString("service"),
                    authConfigJson.getString("version"), "WECHAT_QUERY_STOCK_USED_DETAIL", reqJson, JSONObject.class);

            log.info("{} 请求参数：reqJson={},请求结果：respJson={}", "海科对账接口", JSONUtil.toJsonStr(reqJson), JSONUtil.toJsonStr(response));

            if (response == null) {
                log.info("{} 请求失败,返回内容为空，请求参数：reqJson={}", "海科对账接口", JSONUtil.toJsonStr(reqJson));
                throw new BizException("核验失败");
            }

            if (!"0".equals(response.getCode())) {
                log.info("{} 请求失败，请求参数：reqJson={},返回参数：{}", "海科对账接口", JSONUtil.toJsonStr(reqJson), JSONUtil.toJsonStr(response));
                throw new BizException("核验失败");
            }

            if (response.getData() == null) {
                log.info("{} 请求失败,返回data内容为空，返回参数：{}", "海科对账接口", JSONUtil.toJsonStr(response));
                throw new BizException("核验失败");
            }

            log.info("{},成功返回信息：{}", "海科对账接口", JSONUtil.toJsonStr(response));

            return response.getData();

        } catch (Exception e) {
            log.error("海科对账失败", e);
            throw new BizException("海科对账失败");
        }
    }
}
